<template>
  <div class="meading-report-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" class="search-form">
        <el-form-item label="报工类型">
          <el-select v-model="searchParams.reportType" placeholder="请选择报工类型" clearable style="width: 120px;">
            <el-option 
              v-for="item in reportTypeOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工作站">
          <el-input v-model="searchParams.workStationName" placeholder="请输入工作站名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="报工编码">
          <el-input v-model="searchParams.meadingCode" placeholder="请输入报工编码" clearable></el-input>
        </el-form-item>
        <el-form-item label="产品编码">
          <el-input v-model="searchParams.materialCode" placeholder="请输入产品编码" clearable></el-input>
        </el-form-item>
        <el-form-item label="产品名称">
          <el-input v-model="searchParams.materialName" placeholder="请输入产品名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="报工人">
          <el-input v-model="searchParams.reporter" placeholder="请输入报工人" clearable></el-input>
        </el-form-item>
        <el-form-item label="验收人">
          <el-input v-model="searchParams.checkMan" placeholder="请输入验收人" clearable></el-input>
        </el-form-item>
        <el-form-item label="单据状态">
          <el-select v-model="searchParams.status" placeholder="请选择单据状态" clearable style="width: 120px;">
            <el-option 
              v-for="item in statusOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>查询
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <div class="table-header">
        <el-button type="primary" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>新增
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">
          <el-icon>
            <Delete />
          </el-icon>批量删除
        </el-button>
      </div>

      <!-- 表格 -->
      <el-table
        ref="meadingReportTable"
        :data="tableData"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
        v-loading="loading"
        highlight-current-row
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="reportCode" label="报工编号" width="180"></el-table-column>
        <el-table-column prop="reportType" label="报工类型" width="120"></el-table-column>
        <el-table-column prop="workStation" label="工作站" width="150"></el-table-column>
        <el-table-column prop="process" label="工序" width="120"></el-table-column>
        <el-table-column prop="reportCode" label="报工编码" width="180"></el-table-column>
        <el-table-column prop="materialCode" label="产品编码" width="150"></el-table-column>
        <el-table-column prop="color" label="颜色" width="100">
          <template #default="scope">
            <div class="color-block-container">
              <div 
                class="color-block" 
                :style="{ backgroundColor: scope.row.color || '#fff' }" 
                :title="scope.row.color || '无颜色'"
              ></div>
              <span class="color-text">{{ formatColorText(scope.row.color) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="尺寸" width="100"></el-table-column>
        <el-table-column prop="num" label="数量" width="100"></el-table-column>
        <el-table-column prop="reporter" label="报工人" width="120"></el-table-column>
        <el-table-column prop="reportDate" label="报工日期" width="200">
          <template #default="scope">
            {{ formatDate(scope.row.reportDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="单据状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">
              修改
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">
              删除 
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <span class="total-text">共 {{ total }} 条</span>
        <el-select v-model="pageSize" placeholder="条/页" style="width: 100px">
          <el-option :value="10" label="10条/页"></el-option>
          <el-option :value="20" label="20条/页"></el-option>
          <el-option :value="50" label="50条/页"></el-option>
          <el-option :value="100" label="100条/页"></el-option>
        </el-select>
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        >
        </el-pagination>
        <span class="page-info">前往 <el-input v-model="goToPage" style="width: 50px;"></el-input> 页</span>
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑报工单' : '添加报工单'"
      width="650px"
      :close-on-click-modal="false"
      :show-close="true"
      @close="resetForm"
      center
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        label-position="right"
        class="meading-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报工类型" prop="reportType" required>
              <el-select v-model="formData.reportType" placeholder="请选择报工类型" style="width: 100%">
                <el-option 
                  v-for="item in reportTypeOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报工编号" prop="reportCode">
              <el-input v-model="formData.reportCode" placeholder="系统自动生成" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产工单" prop="productionOrder" required>
              <div class="search-input-container">
                <el-input v-model="formData.productionOrder" placeholder="请选择生产工单" readonly></el-input>
                <el-button @click="openProductionOrderDialog" class="search-button">
                  <el-icon>
                    <Search />
                  </el-icon>
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作站" prop="workStation" required>
              <el-input v-model="formData.workStation" placeholder="请选择工作站"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产任务" prop="productionTask" required>
              <el-input v-model="formData.productionTask" placeholder="请输入生产任务"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工序" prop="process" required>
              <el-select 
                v-model="formData.process" 
                placeholder="请选择工序"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in processOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报工编码" prop="meadingCode">
              <el-input v-model="formData.meadingCode" placeholder="请输入报工编码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品编码" prop="productCode">
              <el-input v-model="formData.productCode" placeholder="请输入产品编码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="formData.productName" placeholder="请输入产品名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="颜色" prop="color">
              <div class="color-picker-container">
                <el-color-picker 
                  v-model="formData.color" 
                  show-alpha 
                  :predefine="predefineColors"
                  popper-class="color-picker-dropdown"
                  size="large"
                  class="color-picker-full">
                </el-color-picker>
                <div 
                  class="color-display" 
                  v-if="formData.color" 
                  :style="{ backgroundColor: formData.color }"
                  :title="formData.color"
                ></div>
                <el-button 
                  v-if="formData.color" 
                  @click="formData.color = ''" 
                  class="clear-color-btn"
                  type="default"
                  size="small"
                  icon="Close"
                  title="清除颜色"
                ></el-button>
              </div>
              <div class="color-value" v-if="formData.color">
                {{ formatColorText(formData.color) }}
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="尺寸" prop="size">
              <el-input v-model="formData.size" placeholder="请输入尺寸"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="spec">
              <el-input v-model="formData.spec" placeholder="请输入规格型号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报工数量" prop="num" required>
              <div class="number-input-container">
                <el-button @click="decreaseNum" :disabled="formData.num <= 1">
                  <el-icon><Minus /></el-icon>
                </el-button>
                <el-input-number v-model="formData.num" :min="0" controls-position="right" style="width: 100%"></el-input-number>
                <el-button @click="increaseNum">
                  <el-icon><Plus /></el-icon>
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="formData.unit" placeholder="请输入单位"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报工人" prop="reporter" required>
              <div class="search-input-container">
                <el-input v-model="formData.reporter" placeholder="请输入报工人"></el-input>
                <el-button @click="openUserDialog('reporter')" class="search-button">
                  <el-icon>
                    <Search />
                  </el-icon>
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报工时间" prop="reportDate" required>
              <el-date-picker
                v-model="formData.reportDate"
                type="datetime"
                placeholder="选择日期时间"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="审核人" prop="checkMan">
              <div class="search-input-container">
                <el-input v-model="formData.checkMan" placeholder="请输入审核人"></el-input>
                <el-button @click="openUserDialog('checkMan')" class="search-button">
                  <el-icon>
                    <Search />
                  </el-icon>
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="descs">
              <el-input
                v-model="formData.descs"
                type="textarea"
                :rows="3"
                placeholder="请输入备注"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">保 存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 生产工单选择对话框 -->
    <el-dialog
      v-model="productionOrderDialogVisible"
      title="工单选择"
      width="1200px"
      destroy-on-close
      :close-on-click-modal="false"
      :show-close="true"
    >
      <!-- 搜索表单 -->
      <div class="production-order-search">
        <el-form :inline="true">
          <el-form-item label="工单编号">
            <el-input v-model="productionOrderSearch.workOrderCode" placeholder="请输入工单编号" clearable></el-input>
          </el-form-item>
          <el-form-item label="工单名称">
            <el-input v-model="productionOrderSearch.workOrderName" placeholder="请输入工单名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="产品编号">
            <el-input v-model="productionOrderSearch.productNumber" placeholder="请输入产品编号" clearable></el-input>
          </el-form-item>
          <el-form-item label="产品名称">
            <el-input v-model="productionOrderSearch.productName" placeholder="请输入产品名称" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchProductionOrders">
              <el-icon>
                <Search />
              </el-icon>查询
            </el-button>
            <el-button @click="resetProductionOrderSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table
        :data="productionOrderData"
        style="width: 100%"
        border
        v-loading="productionOrderLoading"
        highlight-current-row
        @row-click="handleProductionOrderSelect"
        @current-change="handleCurrentRowChange"
        class="no-expand"
        row-key="workOrderCode"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        :indent="0"
      >
        <el-table-column type="index" width="50" label="序号"></el-table-column>
        <el-table-column width="60">
          <template #header>
            <span></span>
          </template>
          <template #default="scope">
            <el-radio 
              v-model="selectedOrderId" 
              :label="scope.row.workOrderCode || ''"
              @change="() => handleRadioChange(scope.row)"
            ></el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="workOrderCode" label="工单编号" width="150"></el-table-column>
        <el-table-column prop="workOrderName" label="工单名称" width="200"></el-table-column>
        <el-table-column prop="productNumber" label="产品编号" width="150"></el-table-column>
        <el-table-column prop="productName" label="产品名称" width="200"></el-table-column>
        <el-table-column prop="specifications" label="规格型号" width="150"></el-table-column>
        <el-table-column prop="unit" label="单位" width="100"></el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" v-if="productionOrderTotal > 0">
        <span class="total-text">共 {{ productionOrderTotal }} 条</span>
        <el-pagination
          layout="prev, pager, next"
          :total="productionOrderTotal"
          :page-size="productionOrderPageSize"
          :current-page="productionOrderCurrentPage"
          @current-change="handleProductionOrderPageChange"
        >
        </el-pagination>
      </div>
      
      <!-- 底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="productionOrderDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmProductionOrder" :disabled="!selectedProductionOrder">选择</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户选择对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      title="人员选择"
      width="70%"
      destroy-on-close
      :close-on-click-modal="false"
      :show-close="true"
    >
      <div class="user-dialog-container">
        <!-- 左侧部门树 -->
        <div class="dept-tree-container">
          <div class="tree-search">
            <el-input 
              v-model="deptFilterText" 
              placeholder="输入关键字过滤部门" 
              clearable
              prefix-icon="Search"
            ></el-input>
          </div>
          <el-scrollbar height="400px">
            <el-tree
              ref="deptTreeRef"
              :data="deptTreeData"
              :props="{ label: 'departmentName', children: 'children' }"
              node-key="departmentId"
              :filter-node-method="filterDeptNode"
              @node-click="handleDeptNodeClick"
              default-expand-all
              highlight-current
            ></el-tree>
          </el-scrollbar>
        </div>
        
        <!-- 右侧用户列表 -->
        <div class="user-list-container">
          <div class="user-search">
            <el-form :inline="true" size="small">
              <el-form-item label="用户名">
                <el-input 
                  v-model="userSearch.useName" 
                  placeholder="请输入用户名" 
                  clearable>
                </el-input>
              </el-form-item>
              <el-form-item label="电话">
                <el-input 
                  v-model="userSearch.phone" 
                  placeholder="请输入电话号码" 
                  clearable>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchUsers">
                  <el-icon><Search /></el-icon>查询
                </el-button>
                <el-button @click="resetUserSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="user-table-wrapper">
            <el-table
              :data="filteredUserList"
              style="width: 100%"
              border
              height="350px"
              v-loading="userListLoading"
              highlight-current-row
              class="no-expand"
              row-key="user_Id"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
              :indent="0"
            >
              <el-table-column width="60" align="center">
                <template #header>
                  <span></span>
                </template>
                <template #default="scope">
                  <el-radio 
                    v-model="selectedUserId" 
                    :label="scope.row.user_Id || ''"
                    @change="() => handleUserRadioChange(scope.row)"
                  ></el-radio>
                </template>
              </el-table-column>
              <el-table-column prop="userName" label="用户名称"></el-table-column>
              <el-table-column prop="deptName" label="部门"></el-table-column>
              <el-table-column prop="phoneNo" label="手机号码"></el-table-column>
              <el-table-column prop="createDate" label="创建时间"></el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      
      <!-- 底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="userDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmUserSelection" :disabled="!selectedUser">选择</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import http from '@/api/http';
import { Search, Delete, Plus, Minus } from '@element-plus/icons-vue';
import { formatDate } from '@/utils/date';

// API基础路径
const baseApiUrl = '/api/MeadingReport';

// 加载状态
const loading = ref(false);

// 表格数据
const tableData = ref([]);

// 选中行IDs
const selectedIds = ref([]);

// 分页参数
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const goToPage = ref(1);

// 搜索参数
const searchParams = reactive({
  reportType: '',
  workStationName: '',
  meadingCode: '',
  materialCode: '',
  materialName: '',
  reporter: '',
  checkMan: '',
  status: null
});

// 表单对话框
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref(null);

// 表格引用
const meadingReportTable = ref(null);

// 下拉选项
const reportTypeOptions = [
  { label: '自行报工', value: '自行报工' },
  { label: '一次报工', value: '一次报工' },
  { label: '批量报工', value: '批量报工' }
];

const statusOptions = [
  { label: '草稿', value: 0 },
  { label: '已确认', value: 100 },
  { label: '已完成', value: 739 }
];

// 工序选项
const processOptions = ref([
  { label: '组装', value: '组装' },
  { label: '检测', value: '检测' },
  { label: '包装', value: '包装' }
]);

// 预设颜色
const predefineColors = [
  '#ff4500', // 红橙色
  '#ff8c00', // 深橙色
  '#ffd700', // 金色
  '#90ee90', // 淡绿色
  '#00ced1', // 青色
  '#1e90ff', // 道奇蓝
  '#c71585', // 紫红色
  '#ff69b4', // 热粉红
  '#000000', // 黑色
  '#ffffff', // 白色
  '#ff0000', // 红色
  '#0000ff', // 蓝色
  '#008000', // 绿色
  '#ffff00', // 黄色
  '#800080', // 紫色
  '#808080'  // 灰色
];

// 常见颜色名称映射
const colorNameMap = {
  '红色': '#ff0000',
  '绿色': '#008000',
  '蓝色': '#0000ff',
  '黄色': '#ffff00',
  '黑色': '#000000',
  '白色': '#ffffff',
  '紫色': '#800080',
  '粉色': '#ffc0cb',
  '橙色': '#ffa500',
  '灰色': '#808080',
  '棕色': '#a52a2a',
  '青色': '#00ffff',
  '紫红色': '#c71585',
  '银色': '#c0c0c0',
  '金色': '#ffd700',
  '卡其色': '#f0e68c',
  '米色': '#f5f5dc'
};

// 生产工单对话框
const productionOrderDialogVisible = ref(false);
const productionOrderTable = ref(null);
const productionOrderLoading = ref(false);
const productionOrderData = ref([]);
const productionOrderTotal = ref(0);
const productionOrderPageSize = ref(10);
const productionOrderCurrentPage = ref(1);
const selectedProductionOrder = ref(null);
const currentRow = ref(null);
const selectedOrderId = ref('');

// 生产工单搜索参数
const productionOrderSearch = reactive({
  workOrderCode: '',
  workOrderName: '',
  productNumber: '',
  productName: '',
  clientName: ''
});

// 表单数据
const formData = reactive({
  id: 0,
  reportCode: '',
  reportType: '',
  productionOrder: '', // 生产工单编号
  productionTask: '', // 生产任务
  workStation: '',
  workStationName: '',
  process: '',
  meadingCode: '',
  productCode: '',
  materialCode: '',
  productName: '',
  materialName: '',
  color: '',
  size: '',
  spec: '', // 规格型号
  unit: '', // 单位
  num: 1,
  reporter: '',
  reportDate: new Date(),
  checkMan: '',
  descs: '',
  status: 0
});

// 表单规则
const formRules = reactive({
  reportType: [
    { required: true, message: '请选择报工类型', trigger: 'change' }
  ],
  productionOrder: [
    { required: true, message: '请选择生产工单', trigger: 'change' }
  ],
  workStation: [
    { required: true, message: '请输入工作站', trigger: 'blur' }
  ],
  productionTask: [
    { required: true, message: '请输入生产任务', trigger: 'blur' }
  ],
  process: [
    { required: true, message: '请选择工序', trigger: 'change' }
  ],
  num: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ],
  reporter: [
    { required: true, message: '请输入报工人', trigger: 'blur' }
  ],
  reportDate: [
    { required: true, message: '请选择报工日期', trigger: 'change' }
  ]
});

// 获取状态显示文本
const getStatusText = (status) => {
  const option = statusOptions.find(opt => opt.value === status);
  return option ? option.label : '未知状态';
};

// 获取状态显示类型
const getStatusType = (status) => {
  switch (status) {
    case 0:
      return 'info';
    case 100:
      return 'warning';
    case 739:
      return 'success';
    default:
      return 'info';
  }
};

// 加载数据
const fetchData = async () => {
  try {
    loading.value = true;
    
    // 构建查询参数
    const params = {
      PageIndex: currentPage.value,
      PageSize: pageSize.value,
      ReportType: searchParams.reportType,
      WorkStationName: searchParams.workStationName,
      MeadingCode: searchParams.meadingCode,
      MaterialCode: searchParams.materialCode,
      MaterialName: searchParams.materialName,
      Reporter: searchParams.reporter,
      CheckMan: searchParams.checkMan,
      Status: searchParams.status
    };
    
    // API调用 - 使用POST请求获取报工单列表
    const response = await http.post(`${baseApiUrl}/GetMeadingReports`, params);

    
    if (response ) {
      // 根据API规范，response中应包含rows和total
      tableData.value = response.rows || [];
      total.value = response.total || 0;
    } else {
      ElMessage.error(response?.msg || '获取数据失败');
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取数据出错:', error);
    ElMessage.error('获取数据失败，请稍后再试');
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchParams).forEach(key => {
    searchParams[key] = '';
  });
  searchParams.status = null;
  currentPage.value = 1;
  fetchData();
};

// 表格选择变化
const handleSelectionChange = (rows) => {
  selectedIds.value = rows.map(row => row.id);
};

// 添加
const handleAdd = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row) => {
  isEdit.value = true;
  resetForm();
  
  console.log('编辑数据:', row);
  
  // 映射API返回的字段到表单字段
  Object.keys(formData).forEach(key => {
    if (key in row) {
      formData[key] = row[key];
    }
  });
  
  // 处理颜色字段，尝试将颜色名称转换为十六进制
  if (formData.color && typeof formData.color === 'string') {
    // 如果是中文颜色名称，转换为十六进制
    if (colorNameMap[formData.color]) {
      formData.color = colorNameMap[formData.color];
    }
    // 如果不是有效的颜色格式，使用黑色
    else if (!formData.color.startsWith('#') && !formData.color.startsWith('rgb')) {
      // 尝试使用名称查找
      const colorLower = formData.color.toLowerCase();
      for (const [name, value] of Object.entries(colorNameMap)) {
        if (name.toLowerCase().includes(colorLower) || colorLower.includes(name.toLowerCase())) {
          formData.color = value;
          break;
        }
      }
    }
  }
  
  // 确保特定字段的映射
  if (row.materialCode && !formData.productCode) {
    formData.productCode = row.materialCode;
  }
  
  if (row.materialName && !formData.productName) {
    formData.productName = row.materialName;
  }
  
  if (row.workStationName && !formData.workStation) {
    formData.workStation = row.workStationName;
  }

  // 设置生产工单编号
  if (row.productionOrder) {
    formData.productionOrder = row.productionOrder;
  } else if (row.meadingCode) {
    // 如果没有productionOrder字段，但有meadingCode，使用meadingCode作为生产工单编号
    formData.productionOrder = row.meadingCode;
  }
  
  // 对于编辑状态，创建一个虚拟的selectedProductionOrder对象，以便表单展示正确
  if (formData.productionOrder) {
    selectedProductionOrder.value = {
      workOrderCode: formData.productionOrder,
      productNumber: formData.productCode || formData.materialCode,
      productName: formData.productName || formData.materialName,
      specifications: formData.spec,
      unit: formData.unit
    };
    selectedOrderId.value = formData.productionOrder;
  }
  
  dialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  
  Object.assign(formData, {
    id: 0,
    reportCode: '',
    reportType: '',
    productionOrder: '',
    productionTask: '',
    workStation: '',
    workStationName: '',
    process: '',
    meadingCode: '',
    productCode: '',
    materialCode: '',
    productName: '',
    materialName: '',
    color: '',
    size: '',
    spec: '',
    unit: '',
    num: 1,
    reporter: '',
    reportDate: new Date(),
    checkMan: '',
    descs: '',
    status: 0
  });

  selectedProductionOrder.value = null;
};

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate();
    
    loading.value = true;
    
    // 准备提交的数据
    const submitData = { ...formData };
    
    // 检查颜色是否是中文名称，如果是则转换为十六进制
    if (submitData.color && typeof submitData.color === 'string' && colorNameMap[submitData.color]) {
      submitData.color = colorNameMap[submitData.color];
    }
    
    // 同步工作站名称
    submitData.workStationName = submitData.workStation;
    
    // 格式化日期字段
    if (submitData.reportDate instanceof Date) {
      submitData.reportDate = formatDate(submitData.reportDate);
    }
    console.log("提交数据",submitData);
    // 根据是否编辑调用不同API
    const url = isEdit.value ? `/api/MeadingReport/UpdMeadingReport` : `/api/MeadingReport/AddMeadingReport`;
    const response = await http.post(url, submitData);
    
    if (response) {
      ElMessage.success(isEdit.value ? '修改成功' : '添加成功');
      dialogVisible.value = false;
      fetchData();
    } else {
      ElMessage.error(response?.msg || '操作失败');
    }
  } catch (error) {
    console.error('提交表单出错:', error);
    ElMessage.error('操作失败，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 删除
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除此报工单吗？', '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    loading.value = true;
    
    // 删除单个报工单
    const response = await http.post(`${baseApiUrl}/DelMeadingReport?ids=${id}`);
    
    if (response && response.status === 0) {
      ElMessage.success('删除成功');
      fetchData();
    } else {
      ElMessage.error(response?.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除出错:', error);
      ElMessage.error('删除失败，请稍后再试');
    }
  } finally {
    loading.value = false;
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }
  
  try {
    await ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 条记录？`, '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    loading.value = true;
    
    // 批量删除报工单
    const ids = selectedIds.value.join(',');
    const response = await http.post(`${baseApiUrl}/DelMeadingReport?ids=${ids}`);
    
    if (response && response.status === 0) {
      ElMessage.success('批量删除成功');
      fetchData();
    } else {
      ElMessage.error(response?.msg || '批量删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除出错:', error);
      ElMessage.error('批量删除失败，请稍后再试');
    }
  } finally {
    loading.value = false;
  }
};

// 分页 - 当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

// 分页 - 每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchData();
};

// 增加/减少数量
const increaseNum = () => {
  formData.num += 1;
};

const decreaseNum = () => {
  if (formData.num > 1) {
    formData.num -= 1;
  }
};

// 打开生产工单选择对话框
const openProductionOrderDialog = () => {
  // 保存当前工单编号，便于数据加载后查找并选中
  const currentProductionOrder = formData.productionOrder;
  
  // 重置数据
  productionOrderData.value = [];
  productionOrderTotal.value = 0;
  
  // 如果是编辑状态且已有工单信息，保留selectedProductionOrder值
  if (!isEdit.value || !selectedProductionOrder.value) {
    selectedProductionOrder.value = null;
    selectedOrderId.value = '';
  } else {
    // 确保单选按钮状态正确
    selectedOrderId.value = currentProductionOrder;
  }
  
  // 打开对话框
  productionOrderDialogVisible.value = true;
  
  // 加载数据
  fetchProductionOrders(currentProductionOrder);
};

// 选择生产工单行
const handleProductionOrderSelect = (row) => {
  selectedProductionOrder.value = row;
  selectedOrderId.value = row.workOrderCode || '';
};

// 处理当前行变更
const handleCurrentRowChange = (row) => {
  if (row) {
    selectedProductionOrder.value = row;
    selectedOrderId.value = row.workOrderId || '';
  }
};

// 单选框变更处理
const handleRadioChange = (row) => {
  selectedProductionOrder.value = row;
};

// 确认选择生产工单
const confirmProductionOrder = () => {
  if (!selectedProductionOrder.value) {
    ElMessage.warning('请选择一条工单记录');
    return;
  }
  
  console.log('选择的生产工单:', selectedProductionOrder.value);
  
  // 将选中的工单信息填充到表单
  formData.productionOrder = selectedProductionOrder.value.workOrderCode || '';
  formData.meadingCode = selectedProductionOrder.value.workOrderCode || ''; // 将工单编号绑定到报工编码
  formData.productCode = selectedProductionOrder.value.productNumber || '';
  formData.materialCode = selectedProductionOrder.value.productNumber || '';
  formData.productName = selectedProductionOrder.value.productName || '';
  formData.materialName = selectedProductionOrder.value.productName || '';
  formData.spec = selectedProductionOrder.value.specifications || '';
  formData.unit = selectedProductionOrder.value.unit || '';
  
  // 关闭对话框
  productionOrderDialogVisible.value = false;
};

// 重置生产工单搜索
const resetProductionOrderSearch = () => {
  // 保存当前已选中的工单编号
  const currentSelectedCode = selectedProductionOrder.value?.workOrderCode || '';
  
  // 重置搜索条件
  productionOrderSearch.workOrderCode = '';
  productionOrderSearch.workOrderName = '';
  productionOrderSearch.productNumber = '';
  productionOrderSearch.productName = '';
  productionOrderSearch.clientName = '';
  productionOrderCurrentPage.value = 1;
  
  // 使用保存的工单编号进行搜索
  fetchProductionOrders(currentSelectedCode);
};

// 生产工单分页变化
const handleProductionOrderPageChange = (val) => {
  productionOrderCurrentPage.value = val;
  
  // 保存当前已选中的工单编号
  const currentSelectedCode = selectedProductionOrder.value?.workOrderCode || '';
  
  // 加载数据
  fetchProductionOrders(currentSelectedCode);
};

// 生产工单分页大小变化
const handleProductionOrderSizeChange = (val) => {
  productionOrderPageSize.value = val;
  productionOrderCurrentPage.value = 1;
  fetchProductionOrders();
};

// 获取生产工单列表
const fetchProductionOrders = async (preSelectCode) => {
  try {
    productionOrderLoading.value = true;
    
    // 构建查询参数
    const params = {
      pageIndex: productionOrderCurrentPage.value,
      pageSize: productionOrderPageSize.value,
      workOrderCode: productionOrderSearch.workOrderCode || (preSelectCode || ''),
      workOrderName: productionOrderSearch.workOrderName || '',
      productNumber: productionOrderSearch.productNumber || '',
      productName: productionOrderSearch.productName || ''
    };
    
    // 使用生产工单的API获取数据
    const response = await http.post('/api/MeadingReport/GetWorkOrder', params);
    console.log('工单数据:', response);
    
    if (response && response.rows) {
      productionOrderData.value = response.rows;
      productionOrderTotal.value = response.total || 0;
      
      // 如果有预选择的工单编号，找到对应的工单并选中
      if (preSelectCode && preSelectCode.trim() !== '') {
        const foundOrder = productionOrderData.value.find(item => item.workOrderCode === preSelectCode);
        if (foundOrder) {
          selectedProductionOrder.value = foundOrder;
          selectedOrderId.value = foundOrder.workOrderCode;
          console.log('已自动选中工单:', foundOrder);
        }
      }
    } else {
      ElMessage.warning('未找到符合条件的工单');
      productionOrderData.value = [];
      productionOrderTotal.value = 0;
    }
  } catch (error) {
    console.error('获取生产工单数据出错:', error);
    ElMessage.error('获取工单数据失败，请稍后再试');
    productionOrderData.value = [];
    productionOrderTotal.value = 0;
  } finally {
    productionOrderLoading.value = false;
  }
};

// 用户选择对话框
const userDialogVisible = ref(false);
const selectedUserId = ref('');
const selectedUser = ref(null);
const deptFilterText = ref('');
const deptTreeData = ref([]);
const userFilterText = ref('');
const userListLoading = ref(false);
const userList = ref([]);
const filteredUserList = ref([]);
const currentSelectField = ref(''); // 当前选择的字段，'reporter' 或 'checkMan'
const deptTreeRef = ref(null);
const selectedDeptId = ref(''); // 当前选中的部门ID

// 用户搜索参数
const userSearch = reactive({
  useName: '',
  phone: '',
  departmentId: ''
});

// 监听部门过滤文本变化
watch(deptFilterText, (val) => {
  deptTreeRef.value.filter(val);
});

// 获取部门树
const fetchDeptTree = async () => {
  try {
    userListLoading.value = true;
    
    // 模拟API调用获取部门树数据
    // 实际项目中应替换为真实API调用
    const response = await http.get('/api/MeadingReport/GetDepartmentsList');
    console.log(response);  
    if (response) {
      deptTreeData.value = response.data || [];
    } else {
      ElMessage.warning('获取部门数据失败');
      deptTreeData.value = mockDeptData();
    }
    
    // 获取所有用户
    fetchUserList();
  } catch (error) {
    console.error('获取部门树出错:', error);
    ElMessage.error('获取部门数据失败，请稍后再试');
    // 使用模拟数据
    deptTreeData.value = mockDeptData();
    fetchUserList();
  }
};

// 获取用户列表
const fetchUserList = async () => {
  try {
    userListLoading.value = true;
    
    // 构建查询参数
    const params = {
      useName: userSearch.useName || '',
      phone: userSearch.phone || '',
      departmentId: userSearch.departmentId || selectedDeptId.value || ''
    };
    
    // 构建URL查询字符串
    const queryString = Object.entries(params)
      .filter(([_, value]) => value !== '')
      .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
      .join('&');
    
    // 使用GET请求，参数通过URL传递
    const url = `/api/MeadingReport/GetUserList${queryString ? '?' + queryString : ''}`;
    const response = await http.get(url);
    console.log(response);
    
    
    if (response ) {
      userList.value = response.data || [];
      filteredUserList.value = userList.value;
    } else {
      ElMessage.warning('获取用户数据失败');
      userList.value = mockUserData();
      filteredUserList.value = userList.value;
    }
  } catch (error) {
    console.error('获取用户列表出错:', error);
    ElMessage.error('获取用户数据失败，请稍后再试');
    // 使用模拟数据
    userList.value = mockUserData();
    filteredUserList.value = userList.value;
  } finally {
    userListLoading.value = false;
  }
};

// 搜索用户
const searchUsers = () => {
  fetchUserList();
};

// 重置用户搜索
const resetUserSearch = () => {
  userSearch.useName = '';
  userSearch.phone = '';
  userSearch.departmentId = '';
  selectedDeptId.value = '';
  fetchUserList();
};

// 处理部门节点点击
const handleDeptNodeClick = (node) => {
  // 获取选中部门的用户
  selectedDeptId.value = node.departmentId;
  userSearch.departmentId = node.departmentId;
  fetchUserList();
};

// 过滤部门节点
const filterDeptNode = (value, data) => {
  if (!value) return true;
  return data.departmentName.includes(value);
};

// 处理用户选择
const handleUserRadioChange = (row) => {
  selectedUser.value = row;
};

// 打开用户选择对话框
const openUserDialog = (type) => {
  currentSelectField.value = type;
  userDialogVisible.value = true;
  // 重置数据
  selectedUserId.value = '';
  selectedUser.value = null;
  deptFilterText.value = '';
  selectedDeptId.value = '';
  
  // 重置搜索条件
  resetUserSearch();
  
  // 获取部门树和用户列表
  fetchDeptTree();
};

// 确认用户选择
const confirmUserSelection = () => {
  if (!selectedUser.value) {
    ElMessage.warning('请选择一个用户');
    return;
  }
  
  // 将选中的用户信息填充到表单
  if (currentSelectField.value === 'reporter') {
    formData.reporter = selectedUser.value.userName;
  } else if (currentSelectField.value === 'checkMan') {
    formData.checkMan = selectedUser.value.userName;
  }
  
  userDialogVisible.value = false;
};

// 模拟部门数据 - 仅开发测试用
const mockDeptData = () => {
  return [
    {
      departmentId: '1',
      departmentName: 'XXXX公司',
      children: [
        {
          departmentId: '2',
          departmentName: '二号厂',
          children: [
            { departmentId: '3', departmentName: '研发部门' },
            { departmentId: '4', departmentName: '测试部门' }
          ]
        },
        {
          departmentId: '5',
          departmentName: '财务部门',
          children: [
            { departmentId: '6', departmentName: '财务部门1' },
            { departmentId: '7', departmentName: '财务部门2' }
          ]
        },
        {
          departmentId: '8',
          departmentName: '市场部',
          children: [
            { departmentId: '9', departmentName: '市场部1组' },
            { departmentId: '10', departmentName: '市场部2组' }
          ]
        },
        { departmentId: '11', departmentName: '财务部' },
        { departmentId: '12', departmentName: '生产部' },
        { departmentId: '13', departmentName: '统计部' },
        { departmentId: '14', departmentName: '设备部' },
        { departmentId: '15', departmentName: '安全部' }
      ]
    }
  ];
};

// 工单搜索
const searchProductionOrders = () => {
  // 保存当前已选中的工单编号
  const currentSelectedCode = selectedProductionOrder.value?.workOrderCode || '';
  
  // 重置页码
  productionOrderCurrentPage.value = 1;
  
  // 使用当前搜索条件和已选中工单进行搜索
  fetchProductionOrders(currentSelectedCode);
};

// 格式化颜色文本，简化显示
const formatColorText = (color) => {
  if (!color) return '无';
  
  // 如果是十六进制颜色
  if (color.startsWith('#')) {
    if (color.length > 7) {
      // 带透明度的十六进制，简化为 #RRGGBB
      return color.substring(0, 7);
    }
    return color;
  }
  
  // 如果是rgb或rgba格式
  if (color.startsWith('rgb')) {
    // 简化为RGB
    return 'RGB';
  }
  
  // 其他情况，显示前6个字符
  return color.length > 6 ? color.substring(0, 6) + '...' : color;
};

// 初始化
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.meading-report-container {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-container {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
}

.total-text {
  margin-right: auto;
  color: #606266;
}

.page-info {
  display: flex;
  align-items: center;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.meading-form :deep(.el-form-item__label) {
  font-weight: normal;
  color: #606266;
}

.meading-form :deep(.el-form-item__label::before) {
  color: #f56c6c;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid #e4e7ed;
  padding: 15px;
}

:deep(.el-dialog__body) {
  padding: 20px 20px 0;
}

:deep(.el-dialog__footer) {
  padding: 10px 20px 20px;
  text-align: center;
}

:deep(.el-dialog__headerbtn) {
  top: 15px;
}

.search-input-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.search-input-container :deep(.el-input) {
  flex: 1;
}

.search-button {
  margin-left: 5px;
}

.production-order-search {
  margin-bottom: 15px;
  margin: auto auto;
}

/* 生产工单表格选中行样式 */
.production-order-table :deep(.el-table__row.current-row) {
  background-color: #f0f9eb;
}

.production-order-table :deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #409eff;
  border-color: #409eff;
}

/* 无数据提示样式 */
.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

/* 对话框样式优化 */
.production-order-dialog {
  max-height: 70vh;
  overflow-y: auto;
}

/* 数量输入框容器 */
.number-input-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.number-input-container .el-input-number {
  margin: 0 5px;
  flex: 1;
}

.number-input-container .el-button {
  padding: 8px;
  border-radius: 4px;
}

.number-input-container :deep(.el-input-number__decrease),
.number-input-container :deep(.el-input-number__increase) {
  display: none;
}

.number-input-container :deep(.el-input__wrapper) {
  padding: 0 10px;
}

/* 搜索输入框样式调整 */
.search-input-container .el-button {
  padding: 8px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.user-dialog-container {
  display: flex;
  gap: 20px;
  height: 450px;
}

.dept-tree-container {
  width: 300px;
  border-right: 1px solid #e4e7ed;
  padding-right: 15px;
}

.tree-search {
  margin-bottom: 10px;
}

.user-list-container {
  flex: 1;
}

.user-search {
  margin-bottom: 10px;
}

.user-search .el-form {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.user-search .el-form-item {
  margin-bottom: 5px;
  margin-right: 5px;
}

.user-table-wrapper {
  height: 350px;
}

/* 用户选择对话框内的单选按钮样式 */
.user-list-container :deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #409eff;
  border-color: #409eff;
}

/* 部门树样式 */
.dept-tree-container :deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #f0f9eb;
  color: #67c23a;
}

/* 对话框标题居中 */
.user-dialog-container :deep(.el-dialog__header) {
  text-align: center;
  font-weight: bold;
}

/* 用户列表表格添加class="no-expand" */
.no-expand {
  /* 添加相应的CSS样式来隐藏扩展图标 */
}

/* 用户列表表格添加class="no-expand" */
.no-expand :deep(.el-table__expand-icon) {
  display: none;
}

/* 优化单选按钮在表格中的显示 */
.el-table :deep(.el-radio) {
  margin-right: 0;
  display: flex;
  justify-content: center;
  width: 100%;
  padding: 0;
}

.el-table :deep(.el-radio__input) {
  margin: 0 auto;
}

.el-table :deep(.el-radio__inner) {
  margin: 0 auto;
}

.el-table :deep(.el-radio__label) {
  display: none;
}

/* 颜色选择器样式 */
.color-picker-full {
  width: calc(100% - 70px);
}

.color-picker-full :deep(.el-color-picker__trigger) {
  width: 100%;
  height: 32px;
  padding: 4px;
}

.color-picker-container {
  display: flex;
  align-items: center;
  width: 100%;
  margin-bottom: 4px;
}

.color-display {
  width: 28px;
  height: 28px;
  border-radius: 4px;
  margin-left: 6px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.clear-color-btn {
  margin-left: 4px;
  padding: 4px;
  height: 28px;
  width: 28px;
}

.color-value {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
  word-break: break-all;
}

.color-block-container {
  display: flex;
  align-items: center;
  gap: 5px;
}

.color-block {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  flex-shrink: 0;
}

.color-text {
  font-size: 12px;
  color: #606266;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 40px;
}
</style>

